﻿using FlickrNet;
using Lsk.Business;
using Lsk.Business.DTO;
using Lsk.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace lsk.Web.Api
{
    public class RecentTransactionController : ApiController
    {
        [HttpGet]
        public IEnumerable<String> GetDistrict()
        {
            RecentTransaction propertyMgr = new RecentTransaction();
            return propertyMgr.GetDistrict();
        }

        [HttpPost]
        public IEnumerable<GetRecentSaleProperty_Result> GetRecentSale(dynamic data)
        {
            Dictionary<string, string> entry = JsonConvert.DeserializeObject<Dictionary<string, string>>(data.ToString());
            string saleType = entry["saleType"].ToString();
            string daerah = entry["district"].ToString();
            string propertyType = entry["type"].ToString();
            string addressKeyword = entry["keyword"].ToString();
            RecentTransaction propertyMgr = new RecentTransaction();
            IEnumerable<GetRecentSaleProperty_Result> results = propertyMgr.GetRecentSaleProperty(addressKeyword, propertyType, daerah);
            return results;
        }

        [HttpPost]
	        public IEnumerable<GetRecentSalePropertyLsk1_Result> GetRecentSaleLsk(dynamic data)
	        {
	            Dictionary<string, string> entry = JsonConvert.DeserializeObject<Dictionary<string, string>>(data.ToString());
	 
	            string daerah = entry["district"].ToString();
	            string propertyType = entry["type"].ToString();
	            string addressKeyword = entry["keyword"].ToString();
	            string userId = entry["userID"].ToString();
	            RecentTransaction propertyMgr = new RecentTransaction();
	            IEnumerable<GetRecentSalePropertyLsk1_Result> results = propertyMgr.GetRecentSalePropertyLSK(addressKeyword, propertyType, daerah, 1);
	            return results;
	        }

    [HttpPost]
        public IEnumerable<GetRecentRentProperty_Result> GetRecentRent(dynamic data)
        {
            Dictionary<string, string> entry = JsonConvert.DeserializeObject<Dictionary<string, string>>(data.ToString());
            string rentType = entry["saleType"].ToString();
            string daerah = entry["district"].ToString();
            string propertyType = entry["type"].ToString();
            string addressKeyword = entry["keyword"].ToString();
            RecentTransaction propertyMgr = new RecentTransaction();
            IEnumerable<GetRecentRentProperty_Result> results = propertyMgr.GetRecentRentProperty(addressKeyword, propertyType, daerah);
            return results;
        }

        [HttpPost]
	        public IEnumerable<GetRecentRentPropertyLsk1_Result> GetRecentRentLsk(dynamic data)
	        {
	            Dictionary<string, string> entry = JsonConvert.DeserializeObject<Dictionary<string, string>>(data.ToString());
	 
	            string daerah = entry["district"].ToString();
	            string propertyType = entry["type"].ToString();
	            string addressKeyword = entry["keyword"].ToString();
	            string userId = entry["userID"].ToString();
	            RecentTransaction propertyMgr = new RecentTransaction();
	            IEnumerable<GetRecentRentPropertyLsk1_Result> results = propertyMgr.GetRecentRentPropertyLSK(addressKeyword, propertyType, daerah, 1);
	            return results;
	        }

    [HttpGet]
        public IEnumerable<GetRoadName_Result> GetRoadName(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetRoadName(id);
        }

        [HttpGet]
        public IEnumerable<GetProject_Result> GetProject(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetProject(id);
        }

        [HttpGet]
        public IEnumerable<AW_PropertyType> GetPropertyType()
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetPropertyType();
        }


        [HttpPost]
        public HttpResponseMessage save(dynamic data)
        {
            //ListingEntry entry = JsonConvert.DeserializeObject<ListingEntry>(data.ToString());
            AW_Property entry = JsonConvert.DeserializeObject<AW_Property>(data.ToString());

            Property propertyMgr = new Property();
            ResponseMessage msg =propertyMgr.SaveListing(entry);
            return Request.CreateResponse(HttpStatusCode.OK, msg);

        }


        public ResponseMessage GetProperty(string id)
        {
            Property propertyMgr = new Property();
            return propertyMgr.GetProperty(id);

        }



        public PhotoInfo base64ToImage(string data,AW_Property entry)
        {
            PhotoManager photMgr = new PhotoManager();
            AW_Picture picture = new AW_Picture();
            picture.PictureId = Guid.NewGuid();
            picture.PictureDesc =  entry.PropertyId.ToString();
            picture.Picture = entry.PropertyTypeId.ToString();
            picture.CreateDate = DateTime.Now;
            picture.PropertyId = entry.PropertyId;
                    
            var base64Data = Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
            var binData = Convert.FromBase64String(base64Data); 
            using (var stream = new MemoryStream(binData))
            {
               PhotoInfo info = photMgr.Upload(stream, picture);
               picture.PhotoId = info.PhotoId;
               picture.MediumUrl = info.MediumUrl;
               picture.pictureURL = info.OriginalUrl;
               picture.SmallUrl = info.SmallUrl;
               picture.LargeUrl = info.LargeUrl;            
               photMgr.Save(picture);   
               return info;

            }
         
                
        }

        public async Task<HttpResponseMessage> upload() 
      {
            var root = HttpContext.Current.Server.MapPath("~/");
            var provider = new MultipartFormDataStreamProvider(root);

            try 
            {
                PhotoInfo photo = new PhotoInfo();
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // Show all the key-value pairs.

                AW_Property entry = JsonConvert.DeserializeObject<AW_Property>(provider.FormData.GetValues("property")[0]);
                photo =base64ToImage(provider.FormData.GetValues("image")[0], entry);

                //foreach(var key in provider.FormData.AllKeys) 
                //{
                //    foreach(var val in provider.FormData.GetValues(key)) 
                //    {                                      
                //        photo = base64ToImage(val);
                //    }
                //}

                //foreach(MultipartFileData fileData in provider.FileData) 
                //{
                //    var fileName = fileData.Headers.ContentDisposition.FileName;
                //}

                //  var httpRequest = HttpContext.Current.Request;
                // if (httpRequest.Files.Count > 0)
                //{
                //    var docfiles = new List<string>();
                //  foreach (string file in httpRequest.Files)
                //    {
                //        var postedFile = httpRequest.Files[file];
                //        var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                //        postedFile.SaveAs("C:\\Test\\" + postedFile.FileName);
 
                //        docfiles.Add(filePath);
                //    }
                // }

                // output photo object
                 return Request.CreateResponse(HttpStatusCode.OK, photo);
                
            } 

               
            catch (Exception e) 
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,"Error!" + e.InnerException);
            }
        }
    
     }
}
